package org.daidai.abstrusewriting.homepage.top;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.daidai.abstrusewriting.R;
import org.daidai.abstrusewriting.fragments.BaseFragment;
import org.daidai.abstrusewriting.homepage.top.adapters.FragmentAdapter;
import org.daidai.abstrusewriting.homepage.top.fragment.TopListFragment;
import org.daidai.abstrusewriting.homepage.top.model.ListItem;
import org.daidai.abstrusewriting.homepage.top.model.RankingListDetail;
import org.daidai.abstrusewriting.homepage.top.service.TopService;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TopListActivity extends AppCompatActivity{

    private static final String TAG = "TopListActivity";
    private TabLayout tabLayout;
    private RankingListDetail.ShareContent mShareContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_list);
//        EventBus.getDefault().register(this);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }


        String key = getIntent().getStringExtra("key");
        Log.d(TAG, "onCreate: " + key);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.top_list_container);
        tabLayout = (TabLayout) findViewById(R.id.top_list_tab_layout);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        final View navigation = findViewById(R.id.top_list_navigation);

        Toolbar toolbar = (Toolbar) findViewById(R.id.top_list_tool_bar);
        setSupportActionBar(toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setDisplayHomeAsUpEnabled(true);
        }

        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://mobile.ximalaya.com/mobile/discovery/v2/rankingList/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Observable<RankingListDetail> observable = retrofit.create(TopService.class).getTopListDetail("android", key, 1, 20, 2);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RankingListDetail>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(RankingListDetail s) {
                        List<RankingListDetail.Category> categories = s.getCategories();

                        List<BaseFragment> fragments = new ArrayList<>();

                        int size = categories.size();
                        Log.d(TAG, "onNext:   size  " + size);
                        if (size != 0 && categories != null) {
                            navigation.setVisibility(View.VISIBLE);
                            for (int i = 0; i < size; i++) {
                                String name = categories.get(i).getName();
                                Log.d(TAG, "onNext: " + name);
                                TopListFragment fragment = new TopListFragment();
                                fragment.setTitle(name);
                                Bundle bundle = new Bundle();
                                bundle.putString("key", categories.get(i).getKey());
                                fragment.setArguments(bundle);

                                fragments.add(fragment);
                            }
                        } else {
                            TopListFragment fragment = new TopListFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("key", getIntent().getStringExtra("key"));
                            fragment.setArguments(bundle);
                            fragments.add(fragment);
                        }

                        mShareContent = s.getShareContent();

                        FragmentManager manager = getSupportFragmentManager();
                        FragmentAdapter adapter = new FragmentAdapter(manager, fragments);
                        viewPager.setAdapter(adapter);

                        tabLayout.setupWithViewPager(viewPager);

                        List<RankingListDetail.ListItem> list = s.getList();
                        EventBus.getDefault().post(list);
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.top_list_share, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                super.onBackPressed();
                break;
            case R.id.top_share:
                //TODO:第三方分享
                RankingListDetail.ShareContent mShareContent = this.mShareContent;

                ShareSDK.initSDK(this);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

                if (mShareContent != null) {
                    oks.setTitle(mShareContent.getTitle());
                    oks.setTitleUrl(mShareContent.getSubtitle() + "\n" + mShareContent.getUrl());
                    oks.setText(mShareContent.getContent());
                    oks.setImageUrl(mShareContent.getPicUrl());
                    oks.setUrl(mShareContent.getUrl());
                } else {
                    // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                    //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                    // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                    oks.setTitle("标题");
                    // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                    oks.setTitleUrl("http://sharesdk.cn");
                    // text是分享文本，所有平台都需要这个字段
                    oks.setText("我是分享文本");
                    //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
                    oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
                    // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                    //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                    // url仅在微信（包括好友和朋友圈）中使用
                    oks.setUrl("http://sharesdk.cn");
                }

                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite("ShareSDK");
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");
                // 启动分享GUI
                oks.show(this);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
